package com.project.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.project.entity.Project;
import com.project.entity.ProjectUser;
import com.project.entity.User;
import com.project.util.DBHelp;
import com.project.util.RowMapper;

public class ProjectUserDao {

	private DBHelp<ProjectUser> db = new DBHelp<ProjectUser>();
	
	public ProjectUser findByProjectId(String projectid,String userid) {
		
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT userid,tu.username,tu.password,projectid,tp.name,tp.cont,tp.createtime,role FROM t_pu AS tup ");
		sql.append("LEFT JOIN t_user AS tu ON tup.userid = tu.id ");
		sql.append("LEFT JOIN t_project AS tp ON tup.projectid = tp.id ");
		sql.append("where tup.projectid = ? and tup.userid = ?");
		return db.executeQueryForObject(sql.toString(), new ProjectUserRowMapper(), projectid,userid);
	}
	
	public boolean del(String projectid) {
		
		String sql = "delete FROM t_pu where projectid = ?";
		return db.executeSQL(sql, projectid);
	}
	
	private  class ProjectUserRowMapper implements RowMapper<ProjectUser> {

		public ProjectUser mapRow(ResultSet rs) throws SQLException {
			ProjectUser pu = new ProjectUser();
			pu.setRole(rs.getString("role"));
			
			Project p = new Project();
			p.setCreatetime(rs.getString("createtime"));
			p.setCont(rs.getString("cont"));
			p.setId(rs.getString("projectid"));
			p.setName(rs.getString("name"));
			
			pu.setProject(p);
			pu.setProjectid(rs.getString("projectid"));
			
			User user = new User();
			user.setId(rs.getString("userid"));
			user.setPassword(rs.getString("password"));
			user.setUsername(rs.getString("username"));
			
			pu.setUser(user);
			pu.setUserid(rs.getString("userid"));
			
			return pu;
		}

	}
	
	public void save(ProjectUser pu) {
		String sql = "insert into t_pu (projectid,userid,role) values(?,?,?)";
		db.executeSQL(sql, pu.getProjectid(),pu.getUserid(),pu.getRole());
	}

}
